package main

import (
	"context"
	"embed"
	"flag"
	"fmt"
	"gitee.com/llakcs/agile-go"
	"gitee.com/llakcs/agile-go/log"
	"gitee.com/llakcs/aglie-layout/conf"
	"gitee.com/llakcs/aglie-layout/server"
	"gitee.com/llakcs/aglie-layout/service"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

// go build -ldflags "-X main.Version=x.y.z"
var (
	// Name is the name of the compiled software.
	Name string
	// Version is the version of the compiled software.
	Version string
	// flagconf is the config flag.
	flagconf string

	id, _ = os.Hostname()
)

//go:embed resources/*
var fs embed.FS

func init() {
	flag.StringVar(&flagconf, "conf", "./configs", "config path, eg: -conf config.yaml")
}

func main() {
	flag.Parse()
	printlnBanner(fs)
	//初始化配置
	c := conf.InitConfig(flagconf, fs)
	//扫描自定义配置
	cf := conf.ScanConfig(c)
	//日志
	logger := conf.LoadLogger(cf.Logf)
	conf.LoadRedis(cf.Data.RedisConf)
	conf.LoadRabbitmq(cf.Data.MqConf)
	conf.LoadDataSource(cf.Data.DataSource, logger)
	//加载sql脚本
	conf.LoadSqlScript(fs)
	//grpc server
	gs := server.NewGrpcServer(cf.Server.GrpcConf)
	//http server
	hs := server.NewHttpServer(cf.Server.HttpConf)
	app := agile.New(
		agile.ID(cf.App.AppID),
		agile.Name(cf.App.AppName),
		agile.Version(cf.App.AppVer),
		agile.Metadata(map[string]string{}),
		agile.Logger(logger),
		agile.Server(
			gs,
			hs,
		),
		agile.BeforeStart(func(_ context.Context) error {
			log.Info("BeforeStart...")
			return nil
		}),
		agile.BeforeStop(func(_ context.Context) error {
			log.Info("BeforeStop...")
			return nil
		}),
		agile.AfterStart(func(_ context.Context) error {
			log.Info("AfterStart...")
			//开始注册服务
			er := service.DiscoveryAndRegNacos()
			if er != nil {
				log.Error("nacos服务注册异常：", er)
			}
			return nil
		}),
		agile.AfterStop(func(_ context.Context) error {
			log.Info("AfterStop...")
			return nil
		}),
	)
	if err := app.Run(); err != nil {
		panic(err)
	}

}

func printlnBanner(res embed.FS) {
	bannerContent, err := res.ReadFile("resources/banner.txt")
	if err != nil {
		fmt.Println("Error reading banner.txt:", err)
		return
	}
	// 将内容转换为字符串
	bannerStr := string(bannerContent)
	// 定义正则表达式来匹配占位符
	placeholderRegex := regexp.MustCompile(`\${([^:{}]+)(?::([^{}]+))?}`)
	// 找到所有匹配的占位符
	matches := placeholderRegex.FindAllStringSubmatch(bannerStr, -1)
	// 替换占位符
	for _, match := range matches {
		fullMatch := match[0]
		//placeholder := match[1]
		defaultValue := match[2]

		// 获取占位符对应的值，如果没有默认值则使用空字符串
		value := defaultValue
		if value == "" {
			value = getVersion("gitee.com/llakcs/agile-go") // 这里替换为你的默认值
		}

		// 替换占位符
		bannerStr = replacePlaceholder(bannerStr, fullMatch, value)
	}

	// 打印替换后的内容
	fmt.Println(bannerStr)
	log.Info("agile-Go is starting")
}

// 替换占位符
func replacePlaceholder(s, placeholder, value string) string {
	return strings.ReplaceAll(s, placeholder, value)
}

func getVersion(dependencyPath string) string {
	modFilePath := "go.mod"

	// 读取 go.mod 文件内容
	content, err := ioutil.ReadFile(modFilePath)
	if err != nil {
		fmt.Println("Error reading go.mod file:", err)
		return ""
	}

	// 使用正则表达式匹配依赖的版本信息
	re := regexp.MustCompile(fmt.Sprintf(`%s\s+(\S+)`, dependencyPath))
	match := re.FindStringSubmatch(string(content))
	if len(match) < 2 {
		fmt.Printf("Dependency %s not found in go.mod\n", dependencyPath)
		return ""
	}

	// 输出依赖版本信息
	return match[1]
}
